<template>
  <el-card class="book-card" shadow="hover" @click="handleGotoDetail">
    <img :src="book.coverUrl ? book.coverUrl : nullImageUrl" @error="handleImageError" alt=" book" class="book-image">

    <el-row class="book-first-row">
      <el-col :span="17">
        <el-tag type="info">{{ BookCategory }}</el-tag>
      </el-col>
      <el-col :span="7" class="price-col">{{ formattedPrice }}</el-col>
    </el-row>
    <el-row class="book-info">
      <el-col :span="24" class="book-title">{{ book.title }}</el-col>
    </el-row>
    <el-row class="book-detail-row">
      <el-col :span="24" class="book-detail">{{ book.description }}</el-col>
    </el-row>
    <el-row class="book-button-row">
      <el-col :span="1"></el-col>
      <el-col :span="2" class="book-button">
        <el-button type="warning" size="small" @click.stop="addToCart">加入购物车</el-button>
      </el-col>
      <el-col :span="6" class="book-button">
        <el-button type="danger" size="small" @click.stop="buyNow">购买</el-button>
      </el-col>
    </el-row>
  </el-card>

  <PaymentDialog :book="book" :payWay="'立即购买'" :count="1" v-model:dialogVisible="centerDialogVisible">
  </PaymentDialog>
</template>

<script setup>
import { ref, defineProps, computed } from 'vue';
import { useRouter } from 'vue-router';
import { addCart } from '@/api/cart'
import { ElMessage } from 'element-plus'
import PaymentDialog from '@/components/order/PaymentDialog.vue'
import { useUserStore } from '@/stores/user'
const userStore = useUserStore();
import { useBookStore } from '@/stores/book'
const bookStore = useBookStore();
const router = useRouter();
// 定义组件接收的属性
const props = defineProps({
  book: {
    type: Object,
    required: true
  }
});


// 使用 Vite 的 URL 解析方式处理静态资源
const defaultImageUrl = new URL('../../assets/error2.png', import.meta.url).href;
const nullImageUrl = new URL('../../assets/noPicture.jpg', import.meta.url).href;

// 处理图片加载失败事件
const handleImageError = (event) => {
  // 直接设置为默认图片
  event.target.src = defaultImageUrl;

  // 可选：添加错误状态，用于样式调整
  // event.target.classList.add('image-load-failed');

  console.log('图片加载失败，已替换为默认图');
};

const formattedPrice = computed(() => {
  return String(props.book.price).includes('￥') ? props.book.price : '￥' + props.book.price
})

const BookCategory = computed(() => { return bookStore.getBookCategeory(props.book.categoryId) })

const handleGotoDetail = () => {
  console.log('跳2转到详情页,并且props.book.id:', props.book.bookId);
  router.push({
    path: `/bookDetail/${props.book.bookId}`
  });
}

// 加入购物车方法
const addToCart = async () => {
  // 拦截游客
  if (userStore.isLoggedIn === false) {
    router.push({
      path: '/login'
    });
    ElMessage({
      type: 'error',
      message: '请先登录',
      plain: true
    })

  } else {
    console.log(props.book.bookId, "props.book.bookId");
    const bookData = { bookId: props.book.bookId, quantity: 1 }
    const result = await addCart(bookData);
    console.log("加入购物车请求结果：", result);
    if (result.data.code === 0) {

      ElMessage({
        type: 'success',
        message: '加入购物车成功',
        plain: true
      })
    } else {

      ElMessage({
        type: 'error',
        message: result.data.message,
        plain: true
      })
    }
  }


};

const count = ref(1)
// 弹窗相关____________
const centerDialogVisible = ref(false)

// 与购买相关
const buyNow = () => {
  if (!userStore.isLoggedIn) {
    ElMessage({
      type: 'error',
      message: '请先登录',
      plain: true
    })
    router.push({
      path: '/login'
    });
    return;
  } else {
    // console.log(`购买内容《${props.book.title}》共 ${count.value} 本`);
    //弹窗让用户写下订单信息
    centerDialogVisible.value = true;
  }

};

</script>

<style scoped>
.book-card {
  width: 300px;
  height: 380px;
  margin: 15px auto;
  background-color: rgb(255, 255, 255);
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  box-shadow: 0 0 15px rgba(0, 0, 0, 0.1);
  border-radius: 8px;
  overflow: hidden;
}

.book-image {
  width: 260px;
  height: 220px;
  /* width: 160px; */
  object-fit: contain;
  margin: 10px auto;
  box-shadow: 0 0 15px rgba(0, 0, 0, 0.1);
}

.book-first-row {
  height: 10%;
  color: #b10e19;
  font-weight: bolder;
  font-size: 14px;
  font-family: Arial, sans-serif;
  padding: 0 10px;
}

.price-col {
  text-align: right;
  font-size: 16px;
  font-weight: bold;


}

.book-button-row {
  height: 10%;
  justify-content: space-between;
  padding-bottom: 10px;
}

.book-detail {
  height: 10%;
  color: #b4b4b4;
  font-size: 12px;
  font-weight: normal;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  padding: 0 10px;
}

.book-title {
  font-size: 16px;
  font-weight: bold;
  padding: 0 10px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
</style>